<template>
  <MainLayout>
    <div class="checkout-content">
      <h2>结算页面</h2>
      
      <el-row :gutter="30">
        <!-- 订单信息 -->
        <el-col :span="16">
          <el-card>
            <template #header>
              <span>收货信息</span>
            </template>
            
            <el-form :model="orderForm" label-width="100px">
              <el-form-item label="收货人">
                <el-input v-model="orderForm.name" placeholder="请输入收货人姓名" />
              </el-form-item>
              <el-form-item label="手机号码">
                <el-input v-model="orderForm.phone" placeholder="请输入手机号码" />
              </el-form-item>
              <el-form-item label="收货地址">
                <el-input v-model="orderForm.address" type="textarea" :rows="3" placeholder="请输入详细地址" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="orderForm.remark" type="textarea" :rows="2" placeholder="选填" />
              </el-form-item>
            </el-form>
          </el-card>

          <el-card style="margin-top: 20px">
            <template #header>
              <span>订单商品</span>
            </template>
            
            <el-table :data="cartItems" style="width: 100%">
              <el-table-column prop="image" label="商品" width="100">
                <template #default="scope">
                  <el-image :src="scope.row.image" style="width: 80px; height: 80px" fit="cover" />
                </template>
              </el-table-column>
              <el-table-column prop="name" label="商品名称" />
              <el-table-column prop="price" label="单价" width="100">
                <template #default="scope">¥{{ scope.row.price }}</template>
              </el-table-column>
              <el-table-column label="数量" width="100">
                <template #default="scope">{{ scope.row.quantity }}</template>
              </el-table-column>
              <el-table-column label="小计" width="100">
                <template #default="scope">
                  ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <!-- 订单汇总 -->
        <el-col :span="8">
          <el-card class="order-summary">
            <template #header>
              <span>订单汇总</span>
            </template>
            
            <div class="summary-item">
              <span>商品总额：</span>
              <span>¥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <div class="summary-item">
              <span>运费：</span>
              <span>¥{{ shippingFee.toFixed(2) }}</span>
            </div>
            <el-divider />
            <div class="summary-item total">
              <span>实付款：</span>
              <span class="total-price">¥{{ finalPrice.toFixed(2) }}</span>
            </div>
            
            <el-button type="primary" size="large" @click="submitOrder" :loading="loading" class="submit-btn">
              提交订单
            </el-button>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </MainLayout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import MainLayout from '../layouts/MainLayout.vue'
import { orderAPI } from '../api'
import { useAuthStore } from '../stores/auth'
import { ElMessage } from 'element-plus'

const router = useRouter()
const authStore = useAuthStore()

const cartItems = ref([])
const loading = ref(false)

const orderForm = ref({
  name: '',
  phone: '',
  address: '',
  remark: ''
})

const shippingFee = ref(10) // 运费

const totalPrice = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
})

const finalPrice = computed(() => {
  return totalPrice.value + shippingFee.value
})

const submitOrder = async () => {
  // 检查登录状态
  if (!authStore.isAuthenticated || !authStore.token) {
    ElMessage.warning('请先登录后再提交订单')
    router.push({
      path: '/login',
      query: { redirect: '/checkout' }
    })
    return
  }

  // 表单验证
  if (!orderForm.value.name || !orderForm.value.phone || !orderForm.value.address) {
    ElMessage.warning('请填写完整的收货信息')
    return
  }

  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空')
    return
  }

  loading.value = true

  try {
    // ✅ 调用后端API提交订单
    const orderData = {
      items: cartItems.value.map(item => ({
        productId: item.id,
        name: item.name,
        price: item.price,
        quantity: item.quantity
      })),
      shippingAddress: {
        name: orderForm.value.name,
        phone: orderForm.value.phone,
        address: orderForm.value.address,
        city: orderForm.value.city || '',
        province: orderForm.value.province || ''
      },
      totalPrice: finalPrice.value
    }
    
    console.log('提交订单数据:', orderData) // 调试用
    console.log('当前token:', localStorage.getItem('token')) // 调试用
    console.log('请求URL: POST http://localhost:3002/api/orders') // 调试用
    
    const response = await orderAPI.createOrder(orderData)
    
    console.log('订单提交响应:', response) // 调试用
    
    if (response && response.success) {
      // 保存订单到localStorage作为备份
      if (response.data) {
        const orders = JSON.parse(localStorage.getItem('orders') || '[]')
        // 检查是否已存在，避免重复添加
        const existingIndex = orders.findIndex(o => o.id === response.data.id || o.orderId === response.data.id)
        if (existingIndex >= 0) {
          orders[existingIndex] = response.data
        } else {
          orders.push(response.data)
        }
        localStorage.setItem('orders', JSON.stringify(orders))
      }
      
      // 清空购物车
      localStorage.removeItem('cart')
      
      ElMessage.success('订单提交成功！')
      
      // 跳转到订单详情
      if (response.data && response.data.id) {
        router.push(`/order/${response.data.id}`)
      } else {
        router.push('/')
      }
    } else {
      ElMessage.error(response?.message || '订单提交失败')
    }
  } catch (error) {
    console.error('订单提交失败详情:', error) // 调试用
    
    // 详细的错误处理
    if (error.response) {
      const status = error.response.status
      const message = error.response.data?.message || error.message
      
      if (status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        authStore.logout()
        router.push({
          path: '/login',
          query: { redirect: '/checkout' }
        })
      } else if (status === 403) {
        ElMessage.error('权限不足，无法提交订单')
      } else if (status === 400) {
        ElMessage.error(message || '订单数据格式错误')
      } else if (status >= 500) {
        ElMessage.error('服务器错误，请稍后重试')
      } else {
        ElMessage.error(message || '订单提交失败，请重试')
      }
    } else if (error.request) {
      // 网络错误
      ElMessage.error('网络连接失败，请检查后台服务器是否运行（端口3002）')
      console.error('网络错误，无法连接到服务器:', error.request)
    } else {
      // 其他错误
      ElMessage.error(error.message || '订单提交失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 检查登录状态
  if (!authStore.isAuthenticated || !authStore.token) {
    ElMessage.warning('请先登录后再进行结算')
    router.push({
      path: '/login',
      query: { redirect: '/checkout' }
    })
    return
  }

  // 从localStorage加载购物车数据
  const savedCart = localStorage.getItem('cart')
  if (savedCart) {
    cartItems.value = JSON.parse(savedCart)
  }
  
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，请先添加商品')
    router.push('/cart')
  }
})
</script>

<style scoped>
.checkout-content {
  padding: 20px 0;
}

.order-summary {
  position: sticky;
  top: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 14px;
}

.summary-item.total {
  font-size: 18px;
  font-weight: bold;
}

.total-price {
  color: #f56c6c;
  font-size: 24px;
}

.submit-btn {
  width: 100%;
  margin-top: 20px;
  height: 50px;
  font-size: 18px;
}
</style>

